<!-- 账号管理 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px;">
      <div style="display:flex;justify-content:space-between;">
        <div>
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addClick()">添加规则</el-button>
          <el-button type="warning" @click="DownloadFile">模板下载</el-button>
          <span style="color:#d2d7e3;font-size:25px;margin-top:10px;padding-left:10px;">
            <el-tooltip class="item" effect="dark" placement="right">
              <i class="el-icon-question"></i>
              <div style="width: 420px;" slot="content">通过拖动表格行来重新排列顺序,
                系统按次序从上到下优先级执行。终端找到一条匹配的规则后将不再向下继续匹配规则。匹配不到规则将使用默认策略。通过拖动表格行来重新排列顺序,
                系统按次序从上到下优先级执行。添加放到所有规则最后，插入表示在当前策略前插入一条规则</div>
            </el-tooltip>
          </span>
        </div>
      </div>
      <el-table stripe border :data="tableData" class="draggable-table" row-key="RuleName"
        style="width: 100%; margin-top: 15px" height="calc(100vh - 155px)">
        <el-table-column label="序号" width="60" type="index"
          :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
        <el-table-column label="规则名称" prop="RuleName" show-overflow-tooltip></el-table-column>
        <el-table-column label="应用对象类型" show-overflow-tooltip prop="DeviceObjType" width="120px">
          <template slot-scope="{row}">
            <span>{{ DeviceObjTypeFormatter(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="应用对象" show-overflow-tooltip prop="DeviceObj" width="160px">
          <template slot-scope="{row}">
            <span>{{ getDeviceObjDisplay(row, DepartmentList, AssetsList) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="检测间隔" show-overflow-tooltip prop="Interval" width="160px"></el-table-column>
        <el-table-column label="规则生效" show-overflow-tooltip prop="IsValid">
          <template slot-scope="{row}">
            <span>{{ row.IsValid === 1 ? '生效' : '不生效' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注信息" show-overflow-tooltip prop="Descp"></el-table-column>
        <el-table-column label="规则详情" show-overflow-tooltip prop="RuleDetail">
          <template slot-scope="scope">
            <span v-if="scope.row.screenTime > 0">进入屏保时间：{{ scope.row.screenTime }}分钟；</span>
            <span v-if="scope.row.AutoCloseWall">开启墙纸定制；</span>
            <span v-if="scope.row.AutoCloseBack">开启锁屏背景；</span>
            <span v-if="scope.row.AutoCloseIcon">开启锁屏图标；</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">修改</el-button>
            <el-button size="mini" type="success" :disabled="scope.row.IsValid ? true : false"
              @click="disabledClick(scope.row, 1)">启用</el-button>
            <!-- <el-button size="mini" :type="scope.row.IsValid ? 'info' : 'success'" :disabled="scope.row.IsValid ? true : false" @click="disabledClick(scope.row,1)">启用</el-button> -->
            <el-button size="mini" type="info" :disabled="scope.row.IsValid ? false : true"
              @click="disabledClick(scope.row, 0)">禁用</el-button>
            <el-button size="mini" type="danger" @click="deleteClick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-dialog top="5vh" :close-on-click-modal="false" :close-on-press-escape=false
      :title="Action === 1 ? '添加规则' : '修改规则'" :visible.sync="dialogVisible" v-el-drag-dialog width="800px">
      <el-form label-width="130px" ref="accountForm" :model="accountForm" :rules="rules">
        <el-row class="ruleMain">
          <el-divider content-position="left">规则基本内容</el-divider>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则名称：' prop="RuleName">
              <el-input v-model.trim="accountForm.RuleName" :disabled="Action !== 1" :maxlength="30"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则状态：' prop="IsVaclid" style="margin-top:-10px;">
              <el-radio v-model="accountForm.IsValid" :label="1">正常</el-radio>
              <el-radio v-model="accountForm.IsValid" :label="0">失效</el-radio>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <device-object-selector :form.sync="accountForm" />
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label="备注信息：" prop="Descp">
              <el-input placeholder="请输入备注" type="textarea" maxlength="50" :rows="3"
                v-model="accountForm.Descp"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="ruleOther">
          <el-divider content-position="left">企业形象内容</el-divider>
          <el-col :xs="19" :sm="19" :lg="19">
            <el-form-item label='检测间隔：' prop="Interval">
              <el-input v-model.trim="accountForm.Interval" oninput="value=value.replace(/[^0-9]/g,'')"
                maxlength="9"><span slot="append">秒钟</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="19" :sm="19" :lg="19">
            <el-form-item label='进入屏保：' prop="screenTime">
              <el-input v-model.trim="accountForm.screenTime" oninput="value=value.replace(/[^0-9]/g,'')"
                maxlength="9"><span slot="append">分钟</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="5" :lg="5" style="margin-top:10px;">
            <span style="color:#aaa;">
              （0表示不启用）
            </span>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24" style="margin-top:-15px;margin-bottom:-25px;">
            <el-form-item label="" prop="Descp">
              <span style="color:#f36b6e;">修改屏保信息后，需要重启电脑才能生效。</span>
            </el-form-item>
          </el-col>
          <el-col :xs="7" :sm="7" :lg="7">
            <el-form-item label='' prop="" label-width="60px">
              <el-checkbox v-model="accountForm.AutoCloseWall" :true-label="1"
                :false-label="0">开启终端电脑桌面墙纸定制</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="7" :sm="7" :lg="7">
            <el-form-item label='' prop="AutoCloseBack" label-width="60px">
              <el-checkbox v-model="accountForm.AutoCloseBack" :true-label="1"
                :false-label="0">开启终端电脑锁屏背景定制</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="7" :sm="7" :lg="7">
            <el-form-item label='' prop="AutoCloseIcon" label-width="60px">
              <el-checkbox v-model="accountForm.AutoCloseIcon" :true-label="1"
                :false-label="0">开启终端电脑锁屏图标定制</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="24" v-show="Action !== 2">
            <el-form-item label='上传文件：'>
              <el-upload class="upload-demo" action="#" multiple ref="upload" :accept="'.zip'" :on-change="filechange"
                :http-request="uploadFileChange" :on-preview="handlePreview" :on-remove="handleRemove"
                :before-remove="beforeRemove" :before-upload="beforeAvatarUpload" :limit="1" :on-exceed="handleExceed"
                :file-list="fileList">
                <el-button size="small" type="primary" @click="checkBeforeClick">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest, uploadfile, setRemoteFileBin, getRemoteFileBin } from '@/api/firstPage'
import { getToken } from '@/utils/auth' // get token from cookie
import { getDeviceObjDisplay, DeviceObjTypeFormatter } from '@/utils/index.js';
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import Sortable from "sortablejs";
import { toTree } from "@/utils/index.js";
import DeviceObjectSelector from '@/components/DeviceObjectSelector'
export default {
  directives: { elDragDialog },
  components: {
    DeviceObjectSelector
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      tableData: [],
      RoleList: [],
      fileList: [],
      Attach: [],
      Action: 1,
      FileUUID: '',
      dialogVisible: false,
      controlUpload: true,
      accountForm: {},
      DeviceObjList: [],
      AssetsList: [],
      DepartmentList: [],
      rules: {
        RuleName: [
          { required: true, message: "请输入规则名称" }
        ],
      }
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.GetDepartment()
    this.GetDevice()
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.initSort();
  },
  methods: {
    DeviceObjTypeFormatter,
    getDeviceObjDisplay,
    // 获取所有部门
    async GetDepartment() {
      const res = await connrequest('GetDepartment')
      this.DepartmentList = res.Data
    },
    // 获取所有资产
    async GetDevice() {
      const data = {
        Paging: {
          QueryPageNo: 1,
          QueryPageLength: 100000
        },
      }
      const res = await connrequest('GetDevice', data)
      this.AssetsList = res.Data
    },
    initSort() {
      const el = document.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      // 根据具体需求配置options配置项
      const sortable = new Sortable(el, {
        animation: 500, // 拖拽时的动画时长
        onEnd: async (evt) => { // 监听拖动结束事件
          // 下面将拖拽后的顺序进行修改
          const currRow = this.tableData.splice(evt.oldIndex, 1)[0]
          this.tableData.splice(evt.newIndex, 0, currRow)
          const newData = []
          this.tableData.forEach((item, index) => {
            newData[index] = {
              id: item.id,
              rank: index + 1
            }
          })
          const data = {
            Data: {
              OpFile: 3,
              List: [...this.tableData]
            }
          }
          const res = await connrequest('ReorderList', data)
          if (res.Status.StatusCode === 0) {
            this.$message.success('排序成功')
            this.getData()
          }
        }
      })
    },
    async getData() {
      const res = await connrequest('GetDesktopCustomRule')
      this.tableData = res.Data
    },
    addClick() {
      this.Action = 1
      this.fileList = []
      this.Attach = []
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs['accountForm']) {
          this.accountForm = {
            IsValid: 1,
            DeviceObjType: 1,
            Interval: 0,
            screenTime: 0,
            AutoCloseWall: 0,
            AutoCloseBack: 0,
            AutoCloseIcon: 0,
            DeviceObj: [],
          }
        }
        this.$refs['accountForm'].resetFields();
      })
    },
    changeClick(row, index) {
      this.Action = 2
      this.FileUUID = row.FileUUID
      this.FileSize = row.FileSize
      this.$nextTick(() => {
        this.accountForm = { ...row }
        this.$refs['accountForm'].resetFields();
      })
      this.dialogVisible = true
    },
    async disabledClick(row, isValid) {
      row.IsValid = isValid
      let data = {
        Data: {
          Action: 2,
          Detail: {
            ...row
          }
        }
      }
      const res = await connrequest('EditDesktopCustomRule', data)
      if (res.Status.StatusCode === 0) {
        this.$message({
          type: 'success',
          message: isValid ? '启用成功' : '禁用成功'
        });
        this.getData()
        this.dialogVisible = false
      }
    },
    deleteClick(row) {
      this.$confirm('此操作将永久删除该规则, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let data = {
          Data: {
            Action: 3,
            Detail: { ...row }
          }
        }
        const res = await connrequest('EditDesktopCustomRule', data)
        if (res.Status.StatusCode === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
          this.dialogVisible = false
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    submit() {
      this.$refs['accountForm'].validate(async (valid) => {
        if (valid) {
          if (this.accountForm.DeviceObjType === 2) {
            if (!this.accountForm.DeviceObj || this.accountForm?.DeviceObj?.length === 0) {
              this.$message.error('请选择部门')
              return false
            }
          }
          if (this.accountForm.DeviceObjType === 8) {
            if (!this.accountForm.DeviceObj || this.accountForm?.DeviceObj?.length === 0) {
              this.$message.error('请选择角色')
              return false
            }
          }
          if (this.accountForm.DeviceObjType === 6) {
            if (!this.accountForm.DeviceObj || this.accountForm?.DeviceObj?.length === 0) {
              this.$message.error('请选择资产')
              return false
            }
          }
          if (this.Attach.length !== 1 && this.Action !== 2) {
            this.$message.error('请上传文件')
            return false
          }
          let data = {
            Data: {
              Action: this.Action,
              Detail: {
                ...this.accountForm,
                FileUUID: this.FileUUID,
                FileSize: this.FileSize,
                Interval: this.accountForm?.Interval || 0,
                screenTime: this.accountForm?.screenTime || 0,
                OrigFileName: this.Action === 1 ? this.Attach[0]?.OrigFileName : this.accountForm.OrigFileName,
              }
            }
          }
          const res = await connrequest('EditDesktopCustomRule', data)
          if (res.Status.StatusCode === 0) {
            this.getData()
            this.dialogVisible = false
          }
        }
      })
    },
    async upgradeInCenter(file, loading) {
      try {
        const formData = new FormData()
        formData.append('CmdCode', 'UploadFileToTmp')
        formData.append('file', file.file)
        formData.append('Token', getToken())
        const res1 = await uploadfile(formData)
        if (res1.Status.StatusCode !== 0) throw new Error(res1.Status.Msg2Client || '文件上传失败')
        const res2 = await setRemoteFileBin({
          LocalFileName: `/tmp/${file.file.name}`,
          RemoteFileName: `/tmp/${file.file.name}`
        })
        if (res2.Status.StatusCode !== 0) throw new Error(res2.Status.Msg2Client || '文件上传失败')
        this.FileSize = file.file.size
        this.FileUUID = res.Data.UUID
        this.$message.success('文件上传成功')
      } catch (error) {
        if (typeof error === 'string') {
          this.$message.error(error)
        } else {
          this.$message.error(error.message)
        }
      } finally {
        this.$refs.upload.clearFiles();
        loading.close();
      }
    },
    filechange(file, fileList) {
      let arr = []
      fileList.map(item => {
        arr.push({ OrigFileName: item.name, ResFileName: item.uid + '' })
      })
      this.Attach = arr
    },
    async uploadFileChange(file) {
      const loading = this.$loading({
        lock: true,
        text: '文件上传中请稍后......',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      if (this.$isFromCenter) {
        this.upgradeInCenter(file, loading)
        return
      }
      let formData = new FormData();
      formData.append('CmdCode', "UploadFileToTmp");
      formData.append('file', file.file);
      formData.append('Token', getToken());
      const res = await uploadfile(formData)
      if (res.Status.StatusCode === 0) {
        this.FileSize = file.file.size
        this.FileUUID = res.Data.UUID
        this.$message.success('文件上传成功')
      }
    },
    handlePreview() { },
    async handleRemove(file, fileList) {
      if (this.controlUpload) {
        const data = {
          Data: {
            ResFileName: file.uid
          }
        }
        const res = await connrequest('DeleteDesktopAttach', data)
        if (res.Status.StatusCode === 0) {
          this.Attach = this.Attach.filter(item => item.uid !== file.uid);
          this.Attach = this.Attach.filter(item => item.ResFileName != file.uid);
          this.FileSize = 0
          this.$message.success('文件删除成功')
        }
      }

    },
    beforeRemove(file, fileList) {
      if (this.controlUpload)
        return this.$confirm(`确定移除 ${file.name}？`);
    },
    checkBeforeClick(e) {
      if (this.$isFromCenter) {
        e.stopPropagation(); // 阻止 el-upload 弹出选择框
        this.$message.error('当前模式不支持上传文件')
        return
      }
    },
    beforeAvatarUpload(file) {
      const typeArry = ['.zip', '.ZIP'];
      const type = file.name.substring(file.name.lastIndexOf('.'));
      const isTar = typeArry.indexOf(type) > -1;
      if (!isTar) {
        this.controlUpload = false
        this.$message.error('上传文件只能是 zip 格式!');
        return false
      }
      else
        this.controlUpload = true
      return true
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    async DownloadFile() {
      let softwareName = '企业形象模板.zip'
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = softwareName;
      a.click();
      a.remove();
    },
  }
}
</script>